const config = require("./config.js")
const db = uniCloud.database();
class WechatApi {
	constructor() {

	}
	/**
	 * @description 获取微信公众号assess_token
	 */
	async getAccessToken() {
		const ConfigModel = db.collection("wechat-config").where({
			appid: config.appid
		});
		let {
			data
		} = await ConfigModel.get();
		if (data.length > 0) {
			let conf = data[0];
			let current_time = Date.now()
			if (current_time > conf.refresh_time + conf.expires_in * 1000) {
				// 请求token
				let getToken = await this._uniGet(config.appid, config.app_secret)
				if (getToken.statusCode == "OK" && getToken.statusCodeValue == 200 && getToken.body.access_token) {
					// 记录到数据库
					let {
						updated
					} = await ConfigModel.update({
						access_token: getToken.body.access_token,
						expires_in: getToken.body.expires_in,
						refresh_time: current_time
					})
					if (updated) {
						return getToken.body.access_token
					} else {
						return false
					}
				} else {
					return false
				}
			} else {
				return conf.access_token
			}
		}
		return this._get(url)
	}
	async _uniGet(appid, secret) {
		let awaitData = await uniCloud.httpProxyForEip.get(
			'https://api.weixin.qq.com/cgi-bin/token', {
				grant_type: 'client_credential',
				appid: appid,
				secret: secret
			}
		)
		return awaitData
	}
	async _uniPost({
		url,
		data
	}) {
		let postData = await uniCloud.httpProxyForEip.post(config.baseUrl + url, data)
		return postData.body
	}
	/**
	 * @description 获取临时场景二维码
	 */
	async getTicketImg() {
		let token = await this.getAccessToken();
		if (token) {
			// 创建登录信息数据
			let time = Date.now();
			const loginModel = db.collection("wechat-login-qrcode")
			let {
				id
			} = await loginModel.add({
				create_time: time,
				token: token
			})
			if (id) {
				let tickerData = await this._uniPost({
					url: `/qrcode/create?access_token=${token}`,
					data: {
						expire_seconds: 1200,
						action_name: "QR_SCENE",
						action_info: {
							scene: {
								scene_str: id
							}
						}
					}
				})
				return tickerData
			} else {
				return {
					errMsg: "登记表创建失败"
				}
			}

		}
	}
	/**
	 * @@description 设置菜单
	 */
	async setMenu() {
		let token = await this.getAccessToken();
		if (token) {
			let menu = `{"button": [{"type": "view","name": "首页","url":"http://wechat.codecore.cn"},{
							"name": "服务支持",
							"sub_button": [{
									"type": "view",
									"name": "魔香连锁店",
									"url": "http://wechat.codecore.cn/mx"
								},{
									"type": "view",
									"name": "用户授权",
									"url": "http://wechat.codecore.cn/login/index.html"
								},
								{
									"type": "miniprogram",
									"name": "小程序",
									"url": "http://mp.weixin.qq.com",
									"appid": "wx8bc971aac9cfddfd",
									"pagepath": "pages/index/index"
								},
								{
									"type": "click",
									"name": "赞一下我们",
									"key": "V1001_GOOD"
								}
							]
						}]}`
			let menuData = await uniCloud.httpProxyForEip.postJson(
				`${config.baseUrl}/menu/create?access_token=${token}`, JSON.parse(menu))
			return menuData.body
		} else {
			return {
				errMsg: "菜单创建失败"
			}
		}
	}
}

module.exports = new WechatApi()
